package com.librarySystem.service;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.librarySystem.dao.BookDaoInterface;
import com.librarySystem.dao.RecordDaoInterface;
import com.librarySystem.dao.UserDaoInterface;
import com.librarySystem.dto.RecordDTO;
import com.librarySystem.entity.Book;
import com.librarySystem.entity.Record;
import com.librarySystem.entity.User;

@Service
public class RecordService implements RecordServiceInterface {
	@Resource
	private RecordDaoInterface recordDao;
	@Resource
	private UserDaoInterface userDao;
	@Resource
	private BookDaoInterface bookDao;

	@Override
	@Transactional
	public List<Record> find(RecordDTO recordDTO) {
		List<Record> result = recordDao.find(recordDTO);

		return result;
	}

	@Override
	@Transactional
	public boolean save(Record record) {

		// Check record not null.

		// Check user and book.

		// Update the book count.

		// Save the record.

		// Check transaction result.

		// Return.

		if (record != null) {
			User user = userDao.login(record.getUser());
			if (user == null) {
				return false;
			}
			Book book = bookDao.findByBookNumber(record.getBook());
			if (book == null) {
				return false;
			}
			if (book.getCount() - record.getAmount() >= 0) {
				book.setCount(book.getCount() - record.getAmount());
				record.setOperateTime(Calendar.getInstance());
				record.setUser(user);
				record.setBook(book);
				record.setOperateType(1);//1是借出
				return bookDao.updateBook(book) && recordDao.save(record);
			}
		}
		return false;

	}

	@Override
	@Transactional
	public boolean savein(Record record) {
		if (record != null) {
			User user = userDao.login(record.getUser());
			if (user == null) {
				return false;
			}
			Book book = bookDao.findByBookNumber(record.getBook());
			if (book == null) {
				return false;
			}
			if (record.getAmount() > 0) {
				book.setCount(book.getCount() + record.getAmount());
				record.setOperateTime(Calendar.getInstance());
				record.setUser(user);
				record.setBook(book);
				record.setOperateType(2);//2是归还
				return bookDao.updateBook(book) && recordDao.save(record);
			}
		}
		return false;
	}

}
